<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@4.18.0/css/xterm.css" />
    <script src="https://cdn.jsdelivr.net/npm/xterm@4.18.0/lib/xterm.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/xterm-addon-fit@0.6.0/lib/xterm-addon-fit.js"></script>
</head>
<body style="margin:0; padding:0; height:100vh;">
<div id="terminal" style="height:100%;"></div>

<script>
    // 修复：移除了错误的this.rows引用
    const term = new Terminal({
        rendererType: "canvas",
        cursorBlink: true
    });
    const fitAddon = new FitAddon.FitAddon();
    term.loadAddon(fitAddon);
    term.open(document.getElementById('terminal'));
    term.focus();
    fitAddon.fit();

    term.prompt = () => {
        term.write("\r\n$ ");
    };
    term.prompt();

    // 动态获取当前主机和协议（修复：使用location获取当前主机）
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${window.location.host}/log/ws/ssh`;

    let ws;
    let lineBuf = '';          // 整行缓冲

    function connect() {
        ws = new WebSocket(wsUrl);
        ws.binaryType = "arraybuffer";  // 使用二进制传输

        ws.onopen = () => {
            term.writeln('\r\n✅ Connected to SSH server\r\n');
            term.prompt();
        };

        // 修复：添加了正确的花括号包裹代码块
        ws.onmessage = (e) => {
            // 处理可能的文本或二进制数据
            if (typeof e.data === 'string') {
                term.write(e.data);
            } else {
                term.write(new Uint8Array(e.data));
            }
        };

        ws.onclose = () => {
            term.writeln('\r\n❌ Disconnected, trying to reconnect...');
            setTimeout(connect, 2000);
        };

        ws.onerror = (e) => {
            term.writeln(`\r\n❌ WebSocket error: ${e.message}`);
        };
    }

    /* 逐字符输入：本地回显 + 缓冲整行 */
    term.onData((data) => {
        const code = data.charCodeAt(0);
        switch (code) {
            case 13:   // Enter
                if (lineBuf) {
                    term.write('\r\n');                     // 本地换行
                    ws.send(JSON.stringify({
                        type: 'input',
                        data: lineBuf + '\r\n'
                    }));
                    lineBuf = '';
                }
                break;
            case 127:  // Backspace
                if (lineBuf.length) {
                    lineBuf = lineBuf.slice(0, -1);
                    term.write('\b \b');                    // 删除一个字符
                }
                break;
            default:
                if (code >= 32) {                         // 可打印字符
                    lineBuf += data;
                    term.write(data);                       // 立即回显
                }
                break;
        }
    });

    // 添加窗口大小调整事件
    window.addEventListener('resize', () => {
        fitAddon.fit();
    });

    connect(); // 启动连接
</script>
</body>
</html>
